package top.xzxsrq.exsyExcelTool.style;

import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;

/**
 * excel导出单元格合并策略, 合并出来显示为第一个字段
 * <p>
 * WriteSheet writeSheet = EasyExcel.writerSheet(0, period + "货值填报")
 * .registerWriteHandler(new ColumnCellMerge(0, 5, new int[]{2}))
 *
 * @program: report-analysis
 * @create: 2021-08-21 15:46
 **/
public class ColumnCellMerge implements CellWriteHandler {
    /**
     * 合并列的范围索引
     */
    private int mergetColumnBeginIndex;
    private int mergetColumnEndIndex;
    /**
     * 合并行的范围索引
     */
    private int[] mergeRowIndex;

    public ColumnCellMerge(int mergetColumnBeginIndex, int mergetColumnEndIndex, int[] mergeRowIndex) {
        this.mergetColumnBeginIndex = mergetColumnBeginIndex;
        this.mergetColumnEndIndex = mergetColumnEndIndex;
        this.mergeRowIndex = mergeRowIndex;
    }

    private String showValue;

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        Cell cell = context.getCell();
        WriteSheetHolder writeSheetHolder = context.getWriteSheetHolder();
        //当前行
        int curRowIndex = cell.getRowIndex();
        //当前列
        int curColIndex = cell.getColumnIndex();
        for (int rowIndex : mergeRowIndex) {
            if (curRowIndex == rowIndex) {
                if (curColIndex > mergetColumnBeginIndex && curColIndex <= mergetColumnEndIndex) {
                    mergeWithPrevCol(writeSheetHolder, cell, curRowIndex, curColIndex);
                }
            }
        }
    }

    /**
     * 当前单元格向左合并
     *
     * @param writeSheetHolder
     * @param cell
     * @param curRowIndex
     * @param curColIndex
     */
    private void mergeWithPrevCol(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex) {
        Sheet sheet = writeSheetHolder.getSheet();
        List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
        boolean isMerged = false;
        for (int i = 0; i < mergedRegions.size() && !isMerged; i++) {
            CellRangeAddress cellAddresses = mergedRegions.get(i);
            if (cellAddresses.isInRange(curRowIndex, curColIndex - 1)) {
                sheet.removeMergedRegion(i);
                cellAddresses.setLastColumn(curColIndex);
                sheet.addMergedRegion(cellAddresses);
                isMerged = true;
            }
        }
        if (!isMerged) {
            CellRangeAddress cellAddresses = new CellRangeAddress(curRowIndex, curRowIndex, curColIndex - 1, curColIndex);
            sheet.addMergedRegion(cellAddresses);
        }
    }
}
